<template>
  <div class="app">
    <el-row>
      <!-- 下拉框 -->
      <el-col :span="8">
        <el-select v-model="selectedValue" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-col>

      <!-- 开始时间选择器 -->
      <el-col :span="7">
        <el-date-picker
          v-model="startDate"
          type="datetime"
          placeholder="开始时间"
          style="width: 100%"
        />
      </el-col>

      <!-- 结束时间选择器 -->
      <el-col :span="7">
        <el-date-picker
          v-model="endDate"
          type="datetime"
          placeholder="结束时间"
          style="width: 100%"
        />
      </el-col>
    </el-row>

    <!-- 导出按钮 -->
    <el-row>
      <el-col :span="24" style="margin-top: 20px; text-align: center">
        <el-button type="primary" @click="exportExcel">导出 Excel</el-button>
      </el-col>
    </el-row>

    <el-dialog v-model="isDownloading" title="导出中..." width="400px">
      <div>正在下载文件，请稍候...</div>
      <el-progress
        :percentage="downloadProgress"
        status="success"
      ></el-progress>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import * as XLSX from "xlsx";
import { ElMessage, ElLoading } from "element-plus";
import axios from "axios";

// const API_URL_QUERY_OTHER = "https://localhost:44389/api/reportExcel";
// const API_URL_QUERY_ALG = "https://localhost:44389/api/reportExcel/Alg/zip";
const API_URL_QUERY_OTHER = "http://10.20.5.21:8080/api/reportExcel";
const API_URL_QUERY_ALG = "http://10.20.5.21:8080/api/reportExcel/Alg/zip";
let loadingInstance = null;

const options = [
  "YCH-XD11",
  "HGX-ZJ12",
  "XYX-AB31",
  "JHR-ZJ28",
  "HZK-ZJ10",
  "SJY-SC081",
  "TSK-BB32",
  "TSX-BB32",
  "SZW-BB05",
  "TSN-SH388",
  "ALG-SH102,TSN-US999",
  "TLK-SH54,NTX-ZJ132,HTX-ZJ233,XTW-HK031"
];

const selectedValue = ref("");
const startDate = ref("");
const endDate = ref("");

const downloadProgress = ref(0); // 百分比
const isDownloading = ref(false);
let fakeProgressTimer = null;

const exportExcel = async () => {
  if (!selectedValue.value || !startDate.value || !endDate.value) {
    ElMessage.error("值为空");
    return;
  }

  const params = {
    custCode: selectedValue.value,
    startDate: startDate.value,
    endDate: endDate.value
  };

  loadingInstance = ElLoading.service({
    lock: true,
    text: "正在导出excel，请稍候...",
    background: "rgba(0,0,0,0.3)"
  });

  const API_URL_QUERY = selectedValue.value.includes("ALG")
    ? API_URL_QUERY_ALG
    : API_URL_QUERY_OTHER; // 默认其他接口

  console.log("API_URL_QUERY", API_URL_QUERY);

  try {
    isDownloading.value = true;
    downloadProgress.value = 0;

    fakeProgressTimer = setInterval(() => {
      if (downloadProgress.value < 60) {
        downloadProgress.value += 2;
      }
    }, 300);

    const response = await axios.get(API_URL_QUERY, {
      params,
      responseType: "blob", // 关键：接收的是文件流
      onDownloadProgress: e => {
        if (fakeProgressTimer) {
          clearInterval(fakeProgressTimer);
          fakeProgressTimer = null;
        }

        if (e.total) {
          const realProgress = Math.round((e.loaded / e.total) * 40); // 40% 给下载用
          downloadProgress.value = 60 + realProgress;
        }
      }
    });

    //判断是否是 zip 文件
    const isZipFile = selectedValue.value.includes("ALG");

    // 如果返回的是 zip 文件
    if (isZipFile) {
      const blob = new Blob([response.data], { type: "application/zip" });

      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = `HTSH_CP_Yield_Weekly_Report_${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.zip`; // zip 文件名称
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(downloadUrl);
    }
    // 如果返回的是 Excel 文件
    else {
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      });

      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = downloadUrl;
      link.download = `${selectedValue.value}_${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.xlsx`; // 设置 Excel 文件名
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(downloadUrl);
    }

    isDownloading.value = false;
    downloadProgress.value = 0;
  } catch (error) {
    if (error.response && error.response.data instanceof Blob) {
      const blob = error.response.data;
      const reader = new FileReader();
      reader.onload = () => {
        try {
          // 尝试解析JSON错误信息
          const errorData = JSON.parse(reader.result);
          ElMessage.error(errorData.message || "未找到相关记录");
        } catch (e) {
          // 非JSON格式，直接读取文本或默认消息
          ElMessage.error(reader.result.toString() || "请求失败");
        }
      };
      reader.onerror = () => {
        ElMessage.error("解析错误信息失败");
      };
      reader.readAsText(blob);
    }
  } finally {
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};
</script>

<style scoped>
.app {
  padding: 20px;
}
</style>
